#include "main.h"
#include "parse.h"

const char *newline = "\n";
const char *equal = "=";
const char *space = " ";

// Check if a file exists (index.html)
int file_exists(char *fname) {
	struct stat   buffer;   
	if (stat (fname, &buffer) == 0)
		return 0;
	else
		return 1;
}

// Check if the path is a directory (darklight)
int is_dir(char* p) {
	char * stripslash;
	struct stat st;
	stripslash = p + 1; // strip the first forward 'slash' from the string
	if (stat(stripslash, &st) == 0 && (st.st_mode & S_IFDIR)) {
		return 1;
	}
	else if (stat(stripslash, &st) == 0 && (st.st_mode & S_IFREG)) {
		return 2;
	}
	return 0;
}

// write to struct
void parse(char *filename)
{
	// open config as readable
	FILE *file = fopen (filename, "r");
    
    printf("Parsing %s\n", filename);
    
    // if file is null, end
	if (file != NULL)
	{
		// line buffer for config
		char line[CONFBUF];
		// int used to track config line
		//int i = 0;
     
		// config while loop, loops fgets until end of file
		while(fgets(line, sizeof(line), file) != NULL)
		{
			
			char *cfline; // setup string
			cfline = strtok(line, newline);
			
			// If its the crunchbang, note for now
			if (strncmp("#!",line,2)==0) {
				continue;
			}
		
			// if line is commented out, skip
			if (strncmp("#",line,1)==0) {
				continue;
			}
			
			if (strncmp(newline,line,1)==0) {
				continue;
			}
			
			char *argvlist[50];
			int argc = 0;
			
			char *moocow = cfline;
			
			// Replace tabs with spaces
			while((cfline = strtok(moocow, space)) != NULL) {
				moocow = NULL;
				argvlist[argc++] = cfline;
			}
			
			cdsh_execute(argvlist);
                           
		} // End while
	} // End if file
           
	fclose(file);
	
	cdsh_exit(0);
}
